<template>
  <div>
    <Modal
        v-model="visible"
        title="发布页面"
        :mask-closable="true"
        :z-index="999"
        :footer-hide="true"
        @on-cancel="cancel">
      <Form :label-width="100" :model="formData">
        <FormItem label="pageId" prop="pageId" hidden>
          <Input v-model="formData.pageId"/>
        </FormItem>
        <FormItem :label="formData.publish == '0' ? '未发布': '已发布'" prop="publish">
          <i-switch v-model="formData.publish" size="small" :true-value="'1'" :false-value="'0'" @on-change="publishChangeHandle">
            <span slot="open"></span>
            <span slot="close"></span>
          </i-switch>
        </FormItem>
        <FormItem label="访问地址">
          <i-input v-model="publishUrl" placeholder="发布页面之后将自动生成访问地址" disabled>
            <Button title="复制" slot="append" v-clipboard="publishUrlClipOptions"><Icon type="md-copy" /></Button>
          </i-input>
        </FormItem>
        <FormItemPanel title="限制访问">
          <FormItem label="是否加密" prop="encrypt">
            <i-switch v-model="formData.encrypt" size="small" :true-value="'1'" :false-value="'0'" @on-change="encryptChangeHandle">
              <span slot="open"></span>
              <span slot="close"></span>
            </i-switch>
          </FormItem>
          <FormItem label="访问密码" prop="password">
            <Input v-model="formData.password" type="password" password style="width: 180px;" :disabled="formData.encrypt == '0'"/>
            <Button class="m-l-5px" type="primary" @click="releasePage" :disabled="formData.encrypt == '0'">保存</Button>
            <Button class="m-l-5px" type="default" @click="resetPassword" :disabled="formData.encrypt == '0'">恢复默认密码</Button>
          </FormItem>
        </FormItemPanel>
      </Form>

      <FormItemPanel>
        <div slot="title">
          以快照方式发布
          <Tooltip content="当选择以快照方式发布时，我们访问的页面内容会锁定在已选快照创建的那个时刻；否则访问的页面将实时同步我们对页面进行的每一次改动"
                   :max-width="200" placement="top">
            <Icon type="md-help-circle" size="15"/>
          </Tooltip>
        </div>
        <Select ref="pageSnapshootSelect" v-model="currentPageEnableSnapshootId" class="w-full m-b-5px" clearable
                @on-change="pageSnapshootSelectChangeHandler" @on-clear="pageSnapshootSelectClearHandler">
          <Option :value="item.id" :label="item.name" v-for="(item, index) in pageSnapshoots" :key="index">
            <p style="font-size: 13px;">
              <span>{{item.name}}</span>
              <span style="color: #8bc34a; float: right;" v-if="item.enabled == '1'"><Icon type="md-checkmark" /></span>
            </p>
            <span style="font-size: 12px; color: #757575;">{{item.remark}}</span>
          </Option>
        </Select>
        <Button size="small" type="primary" class="m-r-5px" :disabled="!currentPageEnableSnapshootId" @click="coverPageSnapshoot">重新覆盖已选中快照</Button>
        <Button size="small" type="primary" class="m-r-5px" @click="addPageSnapshootFormModelVisible = !addPageSnapshootFormModelVisible">新增快照并选中</Button>
      </FormItemPanel>

    </Modal>

    <Modal v-model="addPageSnapshootFormModelVisible"
           width="400"
           title="新增快照"
           :mask-closable="true"
           :ok-text="'保存'"
           @on-ok="addPageSnapshootAndSelect">
      <Form :label-width="60">
        <FormItem label="备注">
          <Input type="textarea" :rows="4" v-model="newPageSnapshootRemark"/>
        </FormItem>
      </Form>
    </Modal>

  </div>
</template>

<script>
  export default {
    name: 'ReleasePageFormModal',
    props: {
      show: Boolean
    },
    data() {
      return {
        visible: this.show,
        pageMetadata: null,
        publishUrl: '',
        formData: {
          pageId: '',
          publish: '',
          encrypt: '',
          password: ''
        },
        currentPageEnableSnapshootId: '',
        pageSnapshoots: [],
        addPageSnapshootFormModelVisible: false,
        newPageSnapshootRemark: ''
      }
    },
    mounted() {

    },
    methods: {
      init (pageMetadata) {
        this.pageMetadata = pageMetadata ? pageMetadata : this.pageMetadata = this.$store.getters['designer/getPageMetadata']
        this.$PnApi.PageApi.getPageById(this.pageMetadata.id).then(result => {
          let dbPageMetadata = result.data.payload;
          this.formData.pageId = dbPageMetadata.id;
          this.formData.publish = dbPageMetadata.publish;
          this.formData.encrypt = dbPageMetadata.encrypt;
          this.formData.password = dbPageMetadata.password;
          this.publishUrl = window.location.protocol + '//' + window.location.host + window.g.PROJECT_ROOT_NAME + this.pageMetadata.path;
        })
        this.loadPageSnapshootData()
      },

      loadPageSnapshootData () {
        this.$PnApi.PageSnapshootApi.getPageSnapshootsByPageId(this.pageMetadata.id).then(result => {
          this.pageSnapshoots = result.data.payload
          this.$PnApi.PageSnapshootApi.getPageSnapshootByEnabled(this.pageMetadata.id, '1').then(result => {
            this.currentPageEnableSnapshootId = '';
            if (result.data.payload) {
              this.currentPageEnableSnapshootId = result.data.payload.id
            }
          })
        })
      },

      releasePage () {
        this.$PnApi.PageApi.releasePage(this.formData.pageId, this.formData.publish, this.formData.encrypt, this.formData.password).then(result => {
          if (result.data.success) {
            this.$store.commit('designer/setPagePublishAndEncrypt', {
              publish: this.formData.publish,
              encrypt: this.formData.encrypt,
              password: result.data.payload
            });
          }else {
            this.$Message.error(result.data.message)
          }
        })
      },

      pageSnapshootSelectChangeHandler (value) {
        if (value) {
          this.$PnApi.PageSnapshootApi.setPageSnapshootEnabledByPageId(this.formData.pageId, '0').then(result => {
            this.$PnApi.PageSnapshootApi.setPageSnapshootEnabled(value, '1').then(result => {
              this.loadPageSnapshootData()
            })
          })
        }
      },

      pageSnapshootSelectClearHandler () {
        this.$PnApi.PageSnapshootApi.setPageSnapshootEnabledByPageId(this.formData.pageId, '0').then(result => {
          this.loadPageSnapshootData()
        })
      },

      coverPageSnapshoot () {
        this.$Modal.confirm({
          title: '确认',
          content: '确定覆盖当前编辑状态内容至当前已选中快照吗？',
          onOk: () => {
            this.$PnApi.PageSnapshootApi.getPageSnapshootById(this.currentPageEnableSnapshootId).then(result => {
              let dbPageSnapshoot = result.data
              dbPageSnapshoot.page_id = this.$PnUtil.getUrlParam('page_id')
              dbPageSnapshoot.layout = JSON.stringify(this.pageMetadata.layout)
              dbPageSnapshoot.theme_json = JSON.stringify(this.pageMetadata.theme_json)
              this.$PnApi.PageSnapshootApi.savePageSnapshoot(dbPageSnapshoot, 'update').then(result => {
                if (result.data.success) {
                  this.$Message.success('覆盖保存成功')
                  this.loadPageSnapshootData()
                }
              })
            })
          }
        });
      },

      addPageSnapshootAndSelect () {
        let pageSnapshootData = {
          page_id: this.pageMetadata.id,
          name: '',
          remark: this.newPageSnapshootRemark,
          layout: JSON.stringify(this.pageMetadata.layout),
          enabled: '0',
          is_lock: '0',
          theme_json: JSON.stringify(this.pageMetadata.theme_json)
        }
        this.$PnApi.PageSnapshootApi.savePageSnapshoot(pageSnapshootData).then(result => {
          if (result.data.success) {
            let newId = result.data.payload
            this.$PnApi.PageSnapshootApi.setPageSnapshootEnabledByPageId(this.pageMetadata.id, '0').then(result => {
              this.$PnApi.PageSnapshootApi.setPageSnapshootEnabled(newId, '1').then(result => {
                this.newPageSnapshootRemark = ''
                this.loadPageSnapshootData()
              })
            })
          }
        })
      },

      cancel () {
        this.visible = false;
        this.$emit('cancel', this.visible);
      },

      resetPassword () {
        this.$Modal.confirm({
          title: '确认',
          content: '是否恢复为默认密码【123】？',
          onOk: () => {
            this.formData.password = '123'
            this.releasePage()
          }
        });
      },

      publishChangeHandle () {
        this.releasePage()
      },

      encryptChangeHandle (val) {
        if (val && this.formData.password == '') {
          this.formData.password = '123'
        }else {
          this.formData.password = ''
        }
        this.releasePage()
      }
    },
    computed: {
      publishUrlClipOptions () {
        return {
          value: this.publishUrl,
          success: () => {
            this.$Message.success('复制成功')
          },
          error: () => {
            this.$Message.error('复制失败')
          }
        }
      },
    },
    watch: {
      show (val) {
        this.visible = val
      }
    }
  }
</script>

<style scoped>
  .ivu-form-item {
    margin-bottom: 0px;
  }
</style>
